package cn.lj.controller;

import cn.lj.common.handler.BusinessException;
import cn.lj.common.response.Result;
import cn.lj.common.response.ResultCode;
import cn.lj.entity.User;
import cn.lj.service.UserService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * @file: UserController
 * @version:
 * @Description: 用户业务控制器
 * @author: 李津
 * @date: 2021-04-13 15:53
 * 本代码要注意的事项、备注事项等
 */

@RestController
@RequestMapping("//user")
//@CrossOrigin
@Api(value = "用户管理", tags = "系统用户接口")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 分页查询用户列表
     * @return
     */
    @GetMapping("/findUserPage")
    @ApiOperation(value = "用户列表",notes = "查询所有的用户信息")
    public Result findUsers(@RequestParam(required = true,defaultValue = "1")Integer current,@RequestParam(required = true,defaultValue = "8")Integer size){
        //对用户进行分页,泛型中注入的就是用户实体类
        Page<User> page = new Page<>(current,size);
        Page<User> userPage = userService.page(page);
        long total = userPage.getTotal();
        List<User> records = userPage.getRecords();

        //使用removeIf方法去除管理账号
        records.removeIf(userObj -> userObj.getLoginName().equals("admin"));

        return Result.ok().data("total", total).data("records",records);
    }

    /**
     * ID查询单个用户信息
     * @param id
     * @return
     */
    @GetMapping("/findUser/{id}")
    @ApiOperation(value = "单个用户",notes = "ID查询单个用户信息")
    public Result findUserById(@PathVariable("id") Integer id){
        User user = userService.getById(id);
        if (Objects.nonNull(user)){
            if (user.getId() == 1){
                throw new BusinessException(ResultCode.USER_ACCOUNT_NOT_EXIST.getCode(),ResultCode.USER_ACCOUNT_NOT_EXIST.getMessage());
            }else {
                return Result.ok().data("user", user);
            }
        }
        else {
            throw new BusinessException(ResultCode.USER_ACCOUNT_NOT_EXIST.getCode(),ResultCode.USER_ACCOUNT_NOT_EXIST.getMessage());
        }
    }

    /**
     * 修改单个用户,用户名和登录名不能重复
     * @param user
     * @return
     */
    @ApiOperation(value = "修改用户",notes = "修改单个用户,用户名和登录名不能重复")
    @PutMapping("/updateUser")
    public Result updateUser(@RequestBody User user) {
        try{
            userService.updateUser(user);
            return Result.ok();
        }catch (Exception e){
            e.printStackTrace();
            return Result.error();
        }
    }

    /**
     * 删除单个用户
     * @param id
     * @return Result
     */
    @ApiOperation(value = "删除用户",notes = "根据id删除用户信息")
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id){

        if (id==1){
            throw new BusinessException(ResultCode.USER_ACCOUNT_NOT_EXIST.getCode(),ResultCode.USER_ACCOUNT_NOT_EXIST.getMessage());
        }
        try{
            userService.removeById(id);
            return Result.ok();
        }catch (Exception e){
            e.printStackTrace();
            return Result.error();
        }
    }

    /**
     * excl导出用户信息
     * @param response
     * @param user
     * @throws IOException
     */
    @ApiOperation(value = "导出用户信息")
    @PostMapping(value = "/export")
    public void exportUserExcel(HttpServletResponse response, @RequestBody(required = false) User user) throws IOException {
        QueryWrapper<User> wrapper = getWrapper(user);
        List<User> users = userService.list(wrapper);
        userService.exportUserExcel(response,users);
//        return Result.ok();
    }

    /**
     * 封装查询条件
     *
     * @param user
     * @return
     */
    private QueryWrapper<User> getWrapper(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (user != null) {
            if (!StringUtils.isEmpty(user.getUserName())) {
                queryWrapper.eq("user_name", user.getUserName());
            }
            if (!StringUtils.isEmpty(user.getLoginName())) {
                queryWrapper.eq("login_name", user.getLoginName());
            }
            if (!StringUtils.isEmpty(user.getIdNo())) {
                queryWrapper.eq("id_no", user.getIdNo());
            }
            if (!StringUtils.isEmpty(user.getPhoneNo())) {
                queryWrapper.eq("phone_no", user.getPhoneNo());
            }
            if (!StringUtils.isEmpty(user.getPassword())) {
                queryWrapper.eq("password", user.getPassword());
            }
        }
        return queryWrapper;
    }
}
















